package com.data.modules.system.util.itext;

import com.itextpdf.text.*;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.*;

import lombok.extern.slf4j.Slf4j;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletOutputStream;

@Slf4j
public class PdfUtil {


    /**
     * 简单的导出 pdf,保存到服务器上某一个临时路径
     * @param map 写入的数据
     * @param templatePath pdf模板路径
     * @param uploadUrl 文件保存的临时路径
     */
    // 利用模板生成pdf
    public String fillTemplate(Map<String,Object> map,String templatePath,String uploadUrl) {
        PdfReader reader;
        ByteArrayOutputStream bos;
        PdfStamper stamper;

        String filePath = null;
        try {
            BaseFont baseFontChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            Font fontChinese =  new  Font(baseFontChinese , 12 , Font.NORMAL);

            reader = new PdfReader(templatePath);// 读取pdf模板
            bos = new ByteArrayOutputStream();
            stamper = new PdfStamper(reader, bos);
            AcroFields form = stamper.getAcroFields();
            Document doc = new Document();

            form.addSubstitutionFont(baseFontChinese);

            //基本文字类的内容处理
            java.util.Iterator<String> it = form.getFields().keySet().iterator();
            while (it.hasNext()) {
                String name = it.next().toString();
                System.out.println(name);
                String value = map.get(name)!=null?map.get(name).toString():null;
                form.setField(name,value);
            }

            stamper.setFormFlattening(true);// 如果为false那么生成的PDF文件还能编辑，一定要设为true
            stamper.close();
            File file = File.createTempFile("temp",".pdf");
            if (!file.exists()) {
                file.mkdirs();
            }
            log.info("file 路径：{}",file.getPath());
            filePath = file.getPath();
            // 创建pdf文件
            FileOutputStream  out = new FileOutputStream(file);

            PdfCopy copy = new PdfCopy(doc, out);
            doc.open();

            PdfImportedPage importPage = null;//copy.getImportedPage(new PdfReader(bos.toByteArray()), 1);
            //copy.addPage(importPage);

            ///循环是处理成品只显示一页的问题
            for (int i=1;i<=reader.getNumberOfPages();i++){
                importPage = copy.getImportedPage(new PdfReader(bos.toByteArray()), i);
                copy.addPage(importPage);
            }

            doc.close();

        } catch (IOException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        }catch (Exception e) {
            e.printStackTrace();
        }
        return filePath;
    }

    /**
     *  比较复杂的导出pdf
     *
     * @param map 写入的数据
     * @param out 自定义保存pdf的文件流
     * @param templatePath pdf模板路径
     */
    // 利用模板生成pdf
    public  void fillTemplate1(Map<String,Object> map,ServletOutputStream out,String templatePath) {
        PdfReader reader;
        ByteArrayOutputStream bos;
        PdfStamper stamper;
        try {
            BaseFont baseFontChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            Font fontChinese =  new  Font(baseFontChinese , 12 , Font.NORMAL);

            reader = new PdfReader(templatePath);// 读取pdf模板
            bos = new ByteArrayOutputStream();
            stamper = new PdfStamper(reader, bos);
            AcroFields form = stamper.getAcroFields();
            Document doc = new Document();

            form.addSubstitutionFont(baseFontChinese);

            //基本文字类的内容处理
            java.util.Iterator<String> it = form.getFields().keySet().iterator();
            while (it.hasNext()) {
                String name = it.next().toString();
                System.out.println(name);
                String value = map.get(name)!=null?map.get(name).toString():null;
                form.setField(name,value);
            }

            if(map.containsKey("imgMap") && map.get("imgMap") != null){
                // 图片类的内容处理
                Map<String, String> imgmap = (Map<String, String>) map.get("imgMap");
                for (String key : imgmap.keySet()) {
                    String value = imgmap.get(key);
                    String imgpath = value;
                    int pageNo = form.getFieldPositions(key).get(0).page;
                    Rectangle signRect = form.getFieldPositions(key).get(0).position;
                    float x = signRect.getLeft();
                    float y = signRect.getBottom();
                    // 根据路径读取图片
                    Image image = Image.getInstance(imgpath);
                    // 获取图片页面
                    PdfContentByte under = stamper.getOverContent(pageNo);
                    // 图片大小自适应
                    image.scaleToFit(signRect.getWidth(), signRect.getHeight());
                    // 添加图片
                    image.setAbsolutePosition(x, y);
                    under.addImage(image);
                }
            }

            if(map.containsKey("tableList") && map.get("tableList") != null){
                // 表格类
                Map<String, List<List<String>>> listMap = (Map<String, List<List<String>>>) map.get("tableList");
                for (String key : listMap.keySet()) {
                    List<List<String>> lists = listMap.get(key);
                    int pageNo = form.getFieldPositions(key).get(0).page;
                    PdfContentByte pcb = stamper.getOverContent(pageNo);
                    Rectangle signRect = form.getFieldPositions(key).get(0).position;
                    //表格位置
                    int column = lists.get(0).size();
                    int row = lists.size();
                    PdfPTable table = new PdfPTable(column);
                    float tatalWidth = signRect.getRight() - signRect.getLeft() - 1;
                    int size = lists.get(0).size();
                    float width[] = new float[size];
                    for (int i = 0; i < size; i++) {
                        if (i == 0) {
                            width[i] = 60f;
                        } else {
                            width[i] = (tatalWidth - 60) / (size - 1);
                        }
                    }
                    table.setTotalWidth(width);
                    table.setLockedWidth(true);
                    table.setKeepTogether(true);
                    table.setSplitLate(false);
                    table.setSplitRows(true);
                    //Font fontProve = new Font(baseFontChinese, 10, Font.NORMAL);

                    //表格数据填写
                    for (int i = 0; i < row; i++) {
                        List<String> list = lists.get(i);
                        for (int j = 0; j < column; j++) {
                            //Font fontProve = new Font(baseFontChinese, 10, Font.NORMAL);
                            Paragraph paragraph = new Paragraph(String.valueOf(list.get(j)),fontChinese);
                            PdfPCell cell = new PdfPCell(paragraph);
                            cell.setBorderWidth(1);
                            cell.setBorderColor(BaseColor.BLACK);
                            cell.setVerticalAlignment(Element.ALIGN_CENTER);
                            cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                            cell.setLeading(0, (float) 1.4);
                            table.addCell(cell);
                        }
                    }
                    int totalPage =5;
                    int rowPerPage = 20;
                    for(int j=1; j< totalPage; j++){
                        doc.newPage();
                        table.writeSelectedRows(rowPerPage * j + 1, (rowPerPage * j + 1) + rowPerPage, doc.left()-11, doc.top()-2, pcb);
                    }
                    //table.writeSelectedRows(0, -1, signRect.getLeft(), signRect.getTop(), pcb);
                }
            }

            stamper.setFormFlattening(true);// 如果为false那么生成的PDF文件还能编辑，一定要设为true
            stamper.close();

            PdfCopy copy = new PdfCopy(doc, out);
            doc.open();

            PdfImportedPage importPage = null;//copy.getImportedPage(new PdfReader(bos.toByteArray()), 1);
            //copy.addPage(importPage);

            ///循环是处理成品只显示一页的问题
            for (int i=1;i<=reader.getNumberOfPages();i++){
                importPage = copy.getImportedPage(new PdfReader(bos.toByteArray()), i);
                copy.addPage(importPage);
            }

            doc.close();

        } catch (IOException e) {
            e.printStackTrace();
        } catch (DocumentException e) {
            e.printStackTrace();
        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    /*
     * * 合並pdf文件 * * @param files 要合並文件數組(絕對路徑如{ "e:\\1.pdf", "e:\\2.pdf" ,
     * "e:\\3.pdf"}) * @param newfile
     * 合並後新產生的文件絕對路徑如e:\\temp.pdf,請自己刪除用過後不再用的文件請 * @return boolean
     * 產生成功返回true, 否則返回false
     */

    public static boolean mergePdfFiles(String[] files, String newfile) {
        boolean retValue = false;
        Document document = null;
        try {
            document = new Document(new PdfReader(files[0]).getPageSize(1));
            PdfCopy copy = new PdfCopy(document, new FileOutputStream(newfile));
            document.open();
            for (int i = 0; i < files.length; i++) {
                PdfReader reader = new PdfReader(files[i]);
                int n = reader.getNumberOfPages();
                for (int j = 1; j <= n; j++) {
                    document.newPage();
                    PdfImportedPage page = copy.getImportedPage(reader, j);
                    copy.addPage(page);
                }
            }
            retValue = true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            document.close();
        }
        return retValue;
    }

}
